<script setup>
import {
    Delete,
    Edit
} from '@element-plus/icons-vue'
import { ref ,onMounted } from 'vue';
import { useExamStore } from '@/stores/examStore'; // 引入 Pinia Store
import {useRouter} from 'vue-router'
import { ElMessage } from 'element-plus'
const router = useRouter();

import { studentListService,examStudentAddService,excelUploadService,searchStudentService,studentDeleteService,examUpdateService} from '@/api/exam.js'

const examStore = useExamStore(); // 使用 Pinia Store

// 当前编辑的考试信息
const currentExam = ref({...examStore.currentExam});

onMounted(() => {
  if (currentExam.value.e_id===undefined) {
    // 如果没有值，跳转到 /teacher/home，并弹窗提示
    ElMessage.warning('请选择一场考试进行编辑');
    router.push('/teacher/home');
  }
});



  // 使用 ref 定义响应式数据
  const activeTab = ref('examEdit'); // 当前激活的选项卡
  const studentForm = ref([
    {
      id: '', 
      account: '',
      s_name: '', 
      classes: '',
      e_id: 0, 
      total: 0,
    }
  ]);
  
  // 处理选项卡点击事件
  const handleTabClick = (tab) => {
    console.log('当前激活的选项卡:', tab.props.name);
  };
  
  const searchForm = ref({
    account: '',
    s_name: '',
    classes: '',
});

const page = ref({
    pageNum: 1, //当前页
    pageSize: 5, //每页条数
})

const studentList = async () => {
    let params = {
        id: currentExam.value.e_id,
        pageNum: page.value.pageNum,
        pageSize: page.value.pageSize,   
    }
    try{  
    let result = await studentListService(params);
    studentForm.value = result.data.list.map(item => ({
            id: item.id,
            account: item.account,
            s_name: item.sname,  // 映射examName到e_name
            classes: item.classes,  // 映射beginTime到startTime
        }));
        studentForm.value.total=result.data.total;
     
    }catch(error){
        console.error('Error in student list request:', error);
    }
}
studentList();

const searchStudent=async()=>{
  const { account, s_name, classes } = searchForm.value;
  let params = {
        pageNum: page.value.pageNum,
        pageSize: page.value.pageSize,
    }
    const examStudentSearch = {
        account: account,
        sname: s_name,
        classes: classes,
        eid: currentExam.value.e_id,
    };

    try{
      let result = await searchStudentService(examStudentSearch,params);
    studentForm.value = result.data.list.map(item => ({
            id: item.id,
            account: item.account,
            s_name: item.sname,  // 映射examName到e_name
            classes: item.classes,  // 映射beginTime到startTime
        }));
        studentForm.value.total=result.data.total;
    }catch (error) {
        console.error('Error in student list request:', error);
    }
}

const addStudent =()=>{
  const { account, s_name, classes } = searchForm.value;

const examStudentAdd = {
        account: account,
        sname: s_name,
        classes: classes,
        eid: currentExam.value.e_id,
    };
   
// 调用后端接口新增考试信息
examStudentAddService(examStudentAdd)
.then(() => {
  ElMessage.success('新增考生成功');
  studentList();
})
.catch(() => {
  ElMessage.error('新增考生失败');
});
}

const fileList = ref([]);
// 文件选择或移除时的回调
const handleFileChange = (file) => {
  fileList.value = [...fileList.value, file];
};

// 文件移除时的回调

// 手动触发上传
const uploadFiles = () => {
  if (fileList.value.length === 0) {
    ElMessage.warning('请先选择文件！');
    return;
  }

  const formData = new FormData();
  fileList.value.forEach(file => {
    formData.append('file', file.raw);
  });
  formData.append('examId', currentExam.value.e_id); 
 
    
    excelUploadService(formData)
    .then(() => {
  ElMessage.success('文件导入成功！');
  fileList.value = [];
  studentList();
})
.catch(() => {
  ElMessage.error('文件导入失败');
});
};

const onCurrentChange = (num) => {
    page.value.pageNum = num
    studentList();
}
const removeStudent =(id)=>{
  studentDeleteService(id)
    .then(() => {
      ElMessage.success('删除考生成功');
      studentList();
    })
    .catch(() => {
      ElMessage.error('删除考生失败');
    });
}
const editStudent=()=>{

}

const saveExam = () => {
    try {
        // 组织 exam 数据，映射字段名
        const examToUpdate = {
            id: currentExam.value.e_id,
            examName: currentExam.value.e_name,
            beginTime: currentExam.value.startTime,
            endTime: currentExam.value.endTime,
            auto: currentExam.value.e_autostart,
        };
        
    
        // 创建 FormData 对象
        const formData = new FormData();
        formData.append('exam', new Blob([JSON.stringify(examToUpdate)],{type: 'application/json'}));

        if(fileList.value.length){
          fileList.value.forEach(file => {
    formData.append('file', file.raw);
  });
        }
        // 调用服务更新考试信息
        examUpdateService(formData).then(() => {
            ElMessage.success('考试信息更新成功');
        })
        .catch(() => {
        ElMessage.error('考试信息更新失败');
        });
    } catch (error) {
        // 处理错误
    }
};

</script>

<template>
  <div>
    <!-- 使用 el-tabs 实现选项卡切换 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <!-- 考生编辑 -->
      <el-tab-pane label="考试编辑" name="examEdit">
        <el-form :model="currentExam" label-width="100px">
        
        <el-form-item label="考试标题" >
          <el-input v-model="currentExam.e_name" placeholder="请输入标题" clearable />
        </el-form-item>
    
        <el-form-item label="开始时间" >
          <el-date-picker v-model="currentExam.startTime" type="datetime" placeholder="选择开始时间" clearable />
        </el-form-item>
     
        <el-form-item label="结束时间" >
          <el-date-picker v-model="currentExam.endTime" type="datetime" placeholder="选择结束时间" clearable />
        </el-form-item>

        <el-form-item label="自动开始">
          <el-radio-group v-model="currentExam.e_autostart">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="上传文件">
          <el-upload
            class="file-uploader"
            action="#"
            :on-change="handleFileChange"
            :file-list="fileList"
            :auto-upload="false"
           
          >
            <el-button type="primary">选择文件</el-button>
          </el-upload>
        </el-form-item>

        <el-form-item label="考卷">
          <div v-for="(file, index) in fileList" :key="index">
            {{ file.name }}
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="saveExam">更新考试</el-button>
        </el-form-item>
      </el-form>
      </el-tab-pane>


      <!-- 考生管理 -->
      <!-- 查询功能 -->
      <el-tab-pane label="考生管理" name="studentManage">
        <el-card class="page-container">
        <el-form :model="searchForm" inline style="margin-bottom: 20px">
            <el-form-item label="学号">
                <el-input v-model="searchForm.account"  clearable />
            </el-form-item>
            <el-form-item label="姓名">
              <el-input v-model="searchForm.s_name"  clearable />
            </el-form-item>
            <el-form-item label="班级">
              <el-input v-model="searchForm.classes"  clearable />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="searchStudent">查询</el-button>
                <el-button type="success" icon="Plus" @click="addStudent">新增</el-button>    
            </el-form-item>
        </el-form>

          <!-- 上传文件和导入功能 -->
    <el-row :gutter="10" style="display: flex; align-items: center;">
      <!-- 上传文件 -->
      <el-col :span="2.5">
        <el-upload
          class="upload-demo"
          action="#"
          :on-change="handleFileChange"
          :file-list="fileList"
          :auto-upload="false"
          accept=".xlsx, .xls"
        >
          <el-button type="warning" icon="Upload">选择文件</el-button>
          
        </el-upload>
      </el-col>

      <!-- 显示文件列表 -->
      <el-col :span="3">
        <div v-if="fileList.length === 0" class="no-file-selected">未选择任何文件</div>
        <div v-else class="file-list">
          <div v-for="(file, index) in fileList" :key="index">
            {{ file.name }}
          </div>
        </div>
      </el-col>

      <!-- 导入按钮 -->
      <el-col :span="1.5">
        <el-button type="primary" @click="uploadFiles">导入</el-button>
      </el-col>
      <div slot="tip" class="el-upload__tip custom-tip">学生名单（学号，姓名，班级）</div>
    </el-row>

        <!-- 学生列表 -->
        <el-table :data="studentForm" style="width: 100%" @row-click="handleRowClick">
            <el-table-column label="学号">
                <template #default="{ row }">{{ row.account }}</template>
            </el-table-column>
            <el-table-column label="姓名">
                <template #default="{ row }">{{ row.s_name }}</template>
            </el-table-column>
            <el-table-column label="班级">
                <template #default="{ row }">{{row.classes }}</template>
            </el-table-column>
            <el-table-column label="删除">
                <template #default="{ row }">
                    <el-button :icon="Delete" circle plain type="danger" @click.stop="removeStudent(row.id)"></el-button>
                </template>
            </el-table-column>
            
            <template #empty>
                <el-empty description="没有考生数据" />
            </template>
        </el-table>
        <div class="pagination-container">
            <el-pagination
                background
                layout="total, prev, pager, next, jumper"
                :total="studentForm.total"
                :page-size.sync="page.pageSize"
                :current-page.sync="page.pageNum"
                @current-change="onCurrentChange"
            />
            <span class="fixed-size-info">每页5条</span>
        </div>
      </el-card>
      </el-tab-pane>
      
      
    </el-tabs>
  </div>
</template>

<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .el-form-item {
        margin-bottom: 10px;
    }
    .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;  /* 居中对齐 */
    align-items: center;      /* 垂直居中对齐 */
}

.fixed-size-info {
    margin-left: 16px;
    font-size: 14px;
    color: #606266; 
    display: inline-block;  /* 确保它和分页控件在同一行 */
}

}
.no-file-selected {
  color: #999;
  margin-left: 10px;
}

.file-list {
  margin-left: 10px;
  display: flex;
  align-items: center;
}

.file-list div {
  margin-right: 10px;
}
.custom-tip {
    font-size: 20px; /* 调整字体大小 */
    color: #606266; /* 可选：调整字体颜色 */
    margin-left: 10px; /* 可选：调整与按钮的间距 */
}
</style>